package homework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FileServer {
    final static int SERVER_PORT=8001;
    final static int BACKLOG=50;
    private ServerSocket serverSocket;
    private Socket socket;
    private InputStream is;
    private OutputStream os;


    public FileServer(){
        try {
            serverSocket=new ServerSocket(SERVER_PORT,BACKLOG);
            System.out.println("--文件上传服务器启动成功--");
            System.out.println("--等待文件上传中--");
            socket=serverSocket.accept();

            //初始化输入输出流
            is=socket.getInputStream();
            os=socket.getOutputStream();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception{
        FileServer fileServer=new FileServer();

        File file=new File("ServerText.txt");


        /**
         * 初始化存储Client上传的文件的txt文档
         * 存在则删除并建立新文件
         * 否则直接建立新文件
         */
        if (file.exists()){
            file.delete();
            file.createNewFile();
            System.out.println("文件创建成功");
        }else{
            file.createNewFile();
        }


        FileOutputStream fos=new FileOutputStream(file);
        BufferedInputStream bi=new BufferedInputStream(fileServer.is);
        int c=0;
        char ch;

        while (c!=-1){
            c=bi.read();
            ch=(char)c;
            System.out.print(ch);
            fos.write(c);
            fos.flush();
        }





    }



}
